﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Xml;

/**
 * @file Material
 * 
 * @author LeonXie
 * */

namespace Catsland.Core {
    /**
     * @brief the base class of Material
     * */
    public class Material {
        public String _name { get; set; }
        // shader
        public Effect _effect { get; set; }
        public Texture2D _texture { get; set; }
        public Material() {
            _name = "UntitledMaterial";
            _effect = null;
            _texture = null;
        }

        public Material(String name, Effect effect, Texture2D texture) {
            _name = name;
            _effect = effect;
            _texture = texture;
        }

        /**
         * @brief configure the matrices of shader
         * 
         * should be invoked before painting an object
         * invoked by engine
         * */
        public virtual void ConfigureMaterial(
            Camera camera,
            Vector3 worldPosition) {
            // setting shader attributes
        }

        public bool SaveToNode(XmlNode node, XmlDocument doc) {
            XmlElement material = doc.CreateElement("Material");
            node.AppendChild(material);

            material.SetAttribute("name", _name);
            material.SetAttribute("texture", _texture.Name);
            material.SetAttribute("effect", _effect.Name);

            return true;
        }

        public static Material LoadFromNode(XmlNode node, Scene scene) {
            XmlElement material = (XmlElement)node;
            String name = material.GetAttribute("name");
            Texture2D texture = scene._contentManager.Load<Texture2D>(material.GetAttribute("texture"));
            texture.Name = material.GetAttribute("texture");
            String effectName = material.GetAttribute("effect");

            Material newMaterial = null;

            if (effectName == "BasicEffect") {
                BasicEffect effect = Mgr<BasicEffect>.Singleton;
                newMaterial = new BasicEffectMaterial(name, effect, texture);
            }
            else {
                Effect effect = scene._contentManager.Load<Effect>(effectName);
                newMaterial = new Material(name, effect, texture);
            }

            return newMaterial;
        }
    }
}
